package com.hengpeng.itfin.service.activity.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.service.activity.RebateService;
import com.hengpeng.itfin.service.impl.BaseServiceImpl;
import com.hengpeng.itfinbase.en.ActivityStatus;
import com.hengpeng.itfinbase.en.DurationType;
import com.hengpeng.itfinbase.en.RewardLevel;
import com.hengpeng.itfinbase.en.RewardRebateStatus;
import com.hengpeng.itfinbase.en.RewardType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.InvestBackRebateRequest;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardRebate;
import com.hengpeng.itfinbase.persist.SystemLog.LogType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinbase.persist.UserRefer;

@Transactional
@Service
@Lazy
public class RebateServiceImpl extends BaseServiceImpl implements RebateService {

    @Override
    public ResponseMessage investSendRebate(InvestBackRebateRequest request) {
        if (request.getUserId() == null || request.getActivityType() == null || request.getInvestInfoId() == null
                || request.getDurType() == null || request.getBorrowDuration() == null) {
            serviceFactory.getSystemLogService().addLog("", "", LogType.ACTIVITYSET_EXCEPTION,
                    "活动请求[" + request.getTransType() + "],参数错误。");
            logger.error("活动请求[" + request.getTransType() + "],参数错误。");
            return MessageUtil.GetSuccessMessage();
        }
        logger.info("开始进入活动[transtype=" + request.getTransType() + "][activityType=" + request.getActivityType()
                + "]业务操作");
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            serviceFactory.getSystemLogService().addLog("", activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION,
                    "活动[" + activity.getActivityType() + "]已暂停或还未开始");
            logger.error("活动[" + activity.getActivityType() + "]已暂停或还未开始");
            return MessageUtil.GetSuccessMessage();
        }
        Reward leveloneReward = null, leveltwoReward = null, levelthreeReward = null, levelfourReward = null;
        Set<Reward> rewards = activity.getRewards();
        Iterator<Reward> iteRewards = rewards.iterator();
        while (iteRewards.hasNext()) {
            Reward r = iteRewards.next();
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELONE) {
                leveloneReward = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTWO) {
                leveltwoReward = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTHREE) {
                levelthreeReward = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELFOUR) {
                levelfourReward = r;
            }
        }
        if (leveloneReward == null || leveltwoReward == null || levelthreeReward == null || levelfourReward == null) {
            serviceFactory.getSystemLogService().addLog("", activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
            logger.error("活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
            return MessageUtil.GetSuccessMessage();
        }
        /**
         * 第一层返利
         */

        UserInfo leveOneUserInfo = daoFactory.getUserInfoDao().get(request.getUserId());

        RewardRebate leveOneRewardRebate = new RewardRebate();
        leveOneRewardRebate.setReferenceId(request.getInvestInfoId().toString());
        leveOneRewardRebate.setActiveId(activity.getId());
        leveOneRewardRebate.setRewardId(leveloneReward.getId());
        leveOneRewardRebate.setCreateTime(new Date());
        leveOneRewardRebate.setGettime(new Date());
        if (request.getDurType() == DurationType.DAY) {
            leveOneRewardRebate.setMoney(new BigDecimal(request.getInvestMoney() * request.getBorrowDuration() / 365
                    * Double.parseDouble(leveloneReward.getRewardVal())).longValue());
        } else if (request.getDurType() == DurationType.MONTH) {
            leveOneRewardRebate.setMoney(new BigDecimal(request.getInvestMoney() * request.getBorrowDuration()
                    * Double.parseDouble(leveloneReward.getRewardVal()) / 12).longValue());
        }

        leveOneRewardRebate.setStatus(RewardRebateStatus.UNACTIVE);
        leveOneRewardRebate.setUpdateTime(new Date());
        leveOneRewardRebate.setUserId(leveOneUserInfo.getId());
        leveOneRewardRebate.setUserName(leveOneUserInfo.getUserName());
        leveOneRewardRebate = serviceFactory.getPersistService().save(leveOneRewardRebate);
        if (leveOneRewardRebate.getId() == null) {
            serviceFactory.getSystemLogService().addLog(
                    "",
                    activity.getId().toString(),
                    LogType.ACTIVITYSET_EXCEPTION,
                    "投资返利发放失败！用户[id=" + leveOneUserInfo.getId() + "][返利金额="
                            + leveOneRewardRebate.getMoney().doubleValue() / 100 + "元]");
            logger.error("投资返利发放失败！用户[id=" + leveOneUserInfo.getId() + "][返利金额="
                    + leveOneRewardRebate.getMoney().doubleValue() / 100 + "元]");
        }
        /**
         * 第二层返利
         */
        UserRefer leveTwoUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(leveOneUserInfo.getId());
        if (leveTwoUserRefer != null) {
            UserInfo leveTwoUserInfo = daoFactory.getUserInfoDao().get(leveTwoUserRefer.getFromUserId());
            RewardRebate leveTwoRewardRebate = new RewardRebate();
            leveTwoRewardRebate.setActiveId(activity.getId());
            leveTwoRewardRebate.setRewardId(leveltwoReward.getId());
            leveTwoRewardRebate.setReferenceId(request.getInvestInfoId().toString());
            leveTwoRewardRebate.setCreateTime(new Date());
            leveTwoRewardRebate.setGettime(new Date());
            /**
             * <pre>
             * 在第二层返利的时候判断这一层返利是否是员工用户,兼职用户，合作商户,若是员工用户则返员工利率,
             * 条件：1，这一层用户角色为员工用户。2，底下没有第三层
             * </pre>
             */
            if ((leveTwoUserInfo.getType() == UserInfoType.EMPLOYEE
                    || leveTwoUserInfo.getType() == UserInfoType.PARTEMPLOYEE || leveTwoUserInfo.getType() == UserInfoType.PARTNER)
                    && daoFactory.getUserReferDao().getUserReferByToUserId(leveTwoUserInfo.getId()) == null) {// 员工用户,兼职用户，合作商户用户推荐
                List<Reward> rewardsspec = serviceFactory.getDaoFactory().getRewardDao()
                        .findRewardByTypes(new RewardType[] { RewardType.EMPLOYEE_INVITE_INVEST_REBATE });
                if (rewardsspec == null || rewardsspec.size() < 1) {
                    serviceFactory.getSystemLogService().addLog("", activity.getId().toString(),
                            LogType.ACTIVITYSET_EXCEPTION, "请配置[rewardType=EMPLOYEE_INVITE_INVEST_REBATE]奖品信息");
                    logger.error("请配置[rewardType=EMPLOYEE_INVITE_INVEST_REBATE]奖品信息");
                } else {
                    if (request.getDurType() == DurationType.DAY) {
                        leveTwoRewardRebate.setMoney(new BigDecimal(request.getInvestMoney()
                                * request.getBorrowDuration() / 365
                                * Double.parseDouble(rewardsspec.get(0).getRewardVal())).longValue());
                    } else if (request.getDurType() == DurationType.MONTH) {
                        leveTwoRewardRebate.setMoney(new BigDecimal(request.getInvestMoney()
                                * request.getBorrowDuration() * Double.parseDouble(rewardsspec.get(0).getRewardVal())
                                / 12).longValue());
                    }
                }

            } else {
                if (request.getDurType() == DurationType.DAY) {
                    leveTwoRewardRebate.setMoney(new BigDecimal(request.getInvestMoney() * request.getBorrowDuration()
                            / 365 * Double.parseDouble(leveltwoReward.getRewardVal())).longValue());
                } else if (request.getDurType() == DurationType.MONTH) {
                    leveTwoRewardRebate.setMoney(new BigDecimal(request.getInvestMoney() * request.getBorrowDuration()
                            * Double.parseDouble(leveltwoReward.getRewardVal()) / 12).longValue());
                }
            }
            leveTwoRewardRebate.setStatus(RewardRebateStatus.UNACTIVE);
            leveTwoRewardRebate.setUpdateTime(new Date());
            leveTwoRewardRebate.setUserId(leveTwoUserInfo.getId());
            leveTwoRewardRebate.setUserName(leveTwoUserInfo.getUserName());
            leveTwoRewardRebate = serviceFactory.getPersistService().save(leveTwoRewardRebate);
            if (leveTwoRewardRebate.getId() == null) {
                serviceFactory.getSystemLogService().addLog(
                        "",
                        activity.getId().toString(),
                        LogType.ACTIVITYSET_EXCEPTION,
                        "投资返利发放失败！用户[id=" + leveTwoUserInfo.getId() + "][返利金额="
                                + leveTwoRewardRebate.getMoney().doubleValue() / 100 + "元]");
                logger.error("投资返利发放失败！用户[id=" + leveTwoUserInfo.getId() + "][返利金额="
                        + leveTwoRewardRebate.getMoney().doubleValue() / 100 + "元]");
            }
            /**
             * 第三层返利
             */
            UserRefer leveThreeUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(leveTwoUserInfo.getId());
            if (leveThreeUserRefer != null) {
                UserInfo leveThreeUserInfo = daoFactory.getUserInfoDao().get(leveThreeUserRefer.getFromUserId());

                RewardRebate leveThreeRewardRebate = new RewardRebate();
                leveThreeRewardRebate.setActiveId(activity.getId());
                leveThreeRewardRebate.setRewardId(levelthreeReward.getId());
                leveThreeRewardRebate.setReferenceId(request.getInvestInfoId().toString());
                leveThreeRewardRebate.setCreateTime(new Date());
                leveThreeRewardRebate.setGettime(new Date());
                if (request.getDurType() == DurationType.DAY) {
                    leveThreeRewardRebate.setMoney(new BigDecimal(request.getInvestMoney()
                            * request.getBorrowDuration() / 365 * Double.parseDouble(levelthreeReward.getRewardVal()))
                            .longValue());
                } else if (request.getDurType() == DurationType.MONTH) {
                    leveThreeRewardRebate.setMoney(new BigDecimal(request.getInvestMoney()
                            * request.getBorrowDuration() * Double.parseDouble(levelthreeReward.getRewardVal()) / 12)
                            .longValue());
                }

                leveThreeRewardRebate.setStatus(RewardRebateStatus.UNACTIVE);
                leveThreeRewardRebate.setUpdateTime(new Date());
                leveThreeRewardRebate.setUserId(leveThreeUserInfo.getId());
                leveThreeRewardRebate.setUserName(leveThreeUserInfo.getUserName());
                leveThreeRewardRebate = serviceFactory.getPersistService().save(leveThreeRewardRebate);
                if (leveThreeRewardRebate.getId() == null) {
                    serviceFactory.getSystemLogService().addLog(
                            "",
                            activity.getId().toString(),
                            LogType.ACTIVITYSET_EXCEPTION,
                            "投资返利发放失败！用户[id=" + leveThreeUserInfo.getId() + "][返利金额="
                                    + leveThreeRewardRebate.getMoney().doubleValue() / 100 + "元]");
                    logger.error("投资返利发放失败！用户[id=" + leveThreeUserInfo.getId() + "][返利金额="
                            + leveThreeRewardRebate.getMoney().doubleValue() / 100 + "元]");
                }
                /**
                 * 第四层返利
                 */
                UserRefer leveFourUserRefer = daoFactory.getUserReferDao().getUserReferByToUserId(
                        leveThreeUserInfo.getId());
                if (leveFourUserRefer != null) {
                    UserInfo leveFourUserInfo = daoFactory.getUserInfoDao().get(leveFourUserRefer.getFromUserId());

                    RewardRebate leveFourRewardRebate = new RewardRebate();
                    leveFourRewardRebate.setActiveId(activity.getId());
                    leveFourRewardRebate.setRewardId(levelfourReward.getId());
                    leveFourRewardRebate.setReferenceId(request.getInvestInfoId().toString());
                    leveFourRewardRebate.setCreateTime(new Date());
                    leveFourRewardRebate.setGettime(new Date());
                    if (request.getDurType() == DurationType.DAY) {
                        leveFourRewardRebate.setMoney(new BigDecimal(request.getInvestMoney()
                                * request.getBorrowDuration() / 365
                                * Double.parseDouble(levelfourReward.getRewardVal())).longValue());
                    } else if (request.getDurType() == DurationType.MONTH) {
                        leveFourRewardRebate
                                .setMoney(new BigDecimal(request.getInvestMoney() * request.getBorrowDuration()
                                        * Double.parseDouble(levelfourReward.getRewardVal()) / 12).longValue());
                    }

                    leveFourRewardRebate.setStatus(RewardRebateStatus.UNACTIVE);
                    leveFourRewardRebate.setUpdateTime(new Date());
                    leveFourRewardRebate.setUserId(leveFourUserInfo.getId());
                    leveFourRewardRebate.setUserName(leveFourUserInfo.getUserName());
                    leveFourRewardRebate = serviceFactory.getPersistService().save(leveFourRewardRebate);
                    if (leveFourRewardRebate.getId() == null) {
                        serviceFactory.getSystemLogService().addLog(
                                "",
                                activity.getId().toString(),
                                LogType.ACTIVITYSET_EXCEPTION,
                                "投资返利发放失败！用户[id=" + leveFourUserInfo.getId() + "][返利金额="
                                        + leveFourRewardRebate.getMoney().doubleValue() / 100 + "元]");
                        logger.error("投资返利发放失败！用户[id=" + leveFourUserInfo.getId() + "][返利金额="
                                + leveFourRewardRebate.getMoney().doubleValue() / 100 + "元]");
                    }
                }
            }
        }
        logger.info("活动[transtype=" + request.getTransType() + "]业务操作结束");
        return MessageUtil.GetSuccessMessage();
    }
}
